package fiuba.adn2.webapp.action;

import fiuba.webapp.action.BaseAction;
import fiuba.adn2.model.Noticia;
import fiuba.service.GenericManager;

import java.util.List;

public class NoticiaAction extends BaseAction {
    private GenericManager<Noticia, Long> noticiaManager;
    private List noticias;

    private Noticia noticia;
    private Long id;

    
    
    public void setNoticiaManager(GenericManager<Noticia, Long> noticiaManager) {
        this.noticiaManager = noticiaManager;
    }

    public List getNoticias() {
        return noticias;
    }

    public String list() {
    	noticias = noticiaManager.getAll();
        return SUCCESS;
    }
    
    
    public void setId(Long id) {
        this.id = id;
    }

    public Noticia getNoticia() {
        return noticia;
    }

    public void setNoticia(Noticia noticia) {
        this.noticia = noticia;
    }

    public String delete() {
    	noticiaManager.remove(noticia.getId());
        saveMessage(getText("noticia.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
        	noticia = noticiaManager.get(id);
        } else {
        	noticia = new Noticia();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (noticia.getId() == null);

        noticia = noticiaManager.save(noticia);

        String key = (isNew) ? "noticia.added" : "noticia.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }    
}
